package liumengbaio.lolzhangyoubao.Activity.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import liumengbaio.lolzhangyoubao.Activity.Activity.HeroVideoDetailsActivity;
import liumengbaio.lolzhangyoubao.Activity.Adapter.HeroGuideAdapter;
import liumengbaio.lolzhangyoubao.Activity.InFo.FreeHeroInfo;
import liumengbaio.lolzhangyoubao.Activity.InFo.HeroGuideInfo;
import liumengbaio.lolzhangyoubao.Activity.View.xListView.XListView;
import liumengbaio.lolzhangyoubao.R;

/**
 * Created by lanouhn on 16/8/23.
 */
public class FragmentHeroGuide extends Fragment implements XListView.IXListViewListener {
    private XListView xListView;
    private HeroGuideAdapter heroGuideAdapter;
    private String id;
    public static FragmentHeroGuide newInstants(FreeHeroInfo info) {
        FragmentHeroGuide fragmentHeroGuide = new FragmentHeroGuide();
        Bundle bundle = new Bundle();
        bundle.putSerializable("guideinfo",info);
        fragmentHeroGuide.setArguments(bundle);
        return fragmentHeroGuide;
    }

    /**
     * 真正加载到adapter的集合
     */
    private List<HeroGuideInfo.DataBean> infos = new ArrayList<>();

    /**
     * 中间暂存数据集合
     */
    private List<HeroGuideInfo.DataBean> temp = new ArrayList<>();

    /**
     * 页码
     */
    private int page = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_heroguide, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
        initData();
        initEvent();
        getDatafromWeb();
    }


    /**
     * 初始化数据
     */
    private void initData() {


        FreeHeroInfo guideinfo = (FreeHeroInfo) getArguments().getSerializable("guideinfo");
        id = guideinfo.getId();


    }

    private void initView(View view) {
        xListView = (XListView) view.findViewById(R.id.xListview);

        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        xListView.setXListViewListener(this);

    }

    private void initEvent() {
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String itemId = infos.get(position-1).getId();
//                String url = "http://api.lol.zhangyoubao.com/mobiles/item/" + itemId + "?v_=400901&size=middle&t=1472459388";
                String url = "http://api.lol.zhangyoubao.com/mobiles/item/"+itemId+"?v_=400901&token=1285c08b612411d0bfc35f213eb5d92a73&user_id=15863305&size=middle&t=1473238514";
                Intent intent = new Intent(getActivity(), HeroVideoDetailsActivity.class);
                intent.putExtra("hero_url", url);
                intent.putExtra("video_url", infos.get(position).getVideo_url());
                startActivity(intent);
            }
        });
    }


    private void getDatafromWeb() {

        String url = "http://lol.zhangyoubao.com/apis/rest/ItemsService/lists?roleid=" + id + "&cattype=guide&page=" + page + "&i_=EsgMWh3USt5BgC/cGtS1hKY9wRoLT+mJ6iTQiBqMiVY=&deviceId=EsgMWh3USt5BgC/cGtS1hKY9wRoLT+mJ6iTQiBqMiVY=&t_=1473125754500&p_=15845&v_=400901&a_=lol&pkg_=com.anzogame.lol&d_=android&osv_=18&cha=ucMartket&u_=&modle_=Coolpad%205311&api=ItemsService.lists&time=1473125754&game=lol&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&secretVersion=v1.0&nonce=125705&secretSignature=aEkVuENzpngXKXRcjx8oY9eaSak=";
        OkHttpClient client = new OkHttpClient();
        //创建一个Request，传入请求地址
        Request request = new Request.Builder()
                .url(url)
                .build();
        //执行请求并返回一个Call对象
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                //获取请求结果
                String result = response.body().string();
                //解析数据
                Gson gson = new Gson();
                HeroGuideInfo info = gson.fromJson(result, HeroGuideInfo.class);

                //判断是否是最后的数据
                //{"data":[],"code":200,"message":"ok","api":1}
                if (info.getCode() == 200 && info.getData().size() == 0) {
                    handler.sendEmptyMessage(2);
                } else {
                    temp = info.getData();
                    if (temp.size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            }
        });
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    xListView.complete();
                    Toast.makeText(getActivity(), "网络请求失败!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:

                    if (page == 1) {
                        //下拉刷新
                        infos.clear();
                        infos.addAll(temp);
                        heroGuideAdapter = new HeroGuideAdapter(infos, getActivity());
                        xListView.setAdapter(heroGuideAdapter);
                        temp.clear();

                        xListView.setPullLoadEnable(true);
                    } else {
                        //上拉加载
                        infos.addAll(temp);
                        heroGuideAdapter.notifyDataSetChanged();
                        temp.clear();
                    }

                    xListView.complete();
                    break;

                case 2:
                    //最后一页
                    xListView.complete();
                    xListView.setPullLoadEnable(false);
                    Toast.makeText(getActivity(), " 已经是最后一页啦 !", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    public void onRefresh() {
        //改变请求地址
        page = 1;
        //调用请求方法
        getDatafromWeb();
    }

    @Override
    public void onLoadMore() {

        //改变请求地址
        page++;
        //调用请求方法
        getDatafromWeb();
    }

}
